<?php
namespace HC\Swoole\Socket;

use HC\Swoole\Exception\MessageException;

class Request
{
    protected $server;
    protected $client;
    protected $from_id;
    protected $message;

    public function __construct(\swoole_server $server, $client, $from_id, $message)
    {
        $this->server  = $server;
        $this->client  = $client;
        $this->from_id = $from_id;

        try {
            $this->message = \HC\Swoole\sw_json_decode($message) ?: [];
        } catch (\Exception $e) {
            throw new MessageException();
        }
    }

    public function fd()
    {
        return $this->from_id;
    }

    public function server() : \swoole_server
    {
        return $this->server;
    }

    public function client() : int
    {
        return $this->client;
    }

    public function cmd() : string
    {
        return $this->message['cmd'] ?? '';
    }

    public function args() : array
    {
        return $this->message['args'] ?? [];
    }

    public function ip() : string
    {
        $connection = $this->connection();

        return $connection['remote_ip'] ?? '127.0.0.1';
    }

    public function connection() : array
    {
        return $this->server->connection_info($this->client, $this->from_id) ?: [];
    }
}
